<!-- 新增/修改考勤组-考勤组 -->
<template>
  <main class="wrap">
    <header><h2>基本信息</h2></header>
    <a-form style="width: 60%; margin: 0 auto" :model="form" autoLabelWidth>
      <a-form-item field="name" label="考勤班组名称" show-colon required>
        <a-input v-model="form.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item
        field="attendanceWorkCalendarId"
        label="工作日历"
        show-colon
        required
      >
        <a-select
          :field-names="fieldNames"
          v-model="form.attendanceWorkCalendarId"
          :options="calendarData.data"
          placeholder="请选择"
        >
        </a-select>
      </a-form-item>
      <a-form-item
        field="attendanceCycleId"
        label="考勤周期"
        show-colon
        required
      >
        <a-select
          :field-names="fieldNames"
          v-model="form.attendanceCycleId"
          :options="cycleData.data"
          placeholder="请选择"
        >
        </a-select>
      </a-form-item>
      <a-form-item
        field="attendanceClassesType"
        label="班次类型"
        show-colon
        required
      >
        <a-select
          v-model="form.attendanceClassesType"
          placeholder="请选择"
          @change="getAttendanceClassesSettingData($event as 1 | 2 | 3 | 4)"
        >
          <a-option :value="1">单班次</a-option>
          <a-option :value="2">两班次</a-option>
          <a-option :value="3">三班次</a-option>
          <a-option :value="4">多班次</a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        field="attendanceClassesSettingId"
        label="选用班次"
        show-colon
        required
      >
        <a-tree-select
          :tree-checkable="true"
          multiple
          :fieldNames="{
            key: 'id',
            title: 'name',
            children: 'children'
          }"
          v-model="form.attendanceClassesSettingId"
          :data="attendanceClassesSettingData"
          placeholder="请选择"
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item
        field="schedulingOfficerId"
        label="排班专员"
        show-colon
        required
      >
        <div @click="isShow(1)" style="width: 100%">
          <a-input v-model="schedulingOfficer" placeholder="请输入" />
        </div>
      </a-form-item>
      <a-form-item
        field="schedulingOfficerId"
        label="适用人员"
        show-colon
        required
      >
        <a-space
          direction="vertical"
          style="
            width: 100%;
            background: #f6faff;
            padding: 10px;
            border: 1px solid #c6e2ff;
            border-radius: 5px;
          "
          fill
        >
          <a-row class="grid-demo">
            <a-col flex="70px">
              <div
                style="line-height: 32px; margin-right: 10px; color: #6b6b6b"
              >
                适用员工
              </div>
            </a-col>
            <a-col flex="auto">
              <a-space direction="vertical" fill>
                <a-input
                  @click="isShow(2)"
                  v-model="attendanceTeam"
                  placeholder="请输入"
                />
                <p
                  v-if="applicableEmployeesExist.data.length !== 0"
                  style="
                    font-size: 12px;
                    color: #f19e43;
                    margin: 0;
                    padding-left: 5px;
                  "
                >
                  选择人员中，有
                  {{ applicableEmployeesExist.data.length }}
                  人由于已加入其他考勤组，未新增成功
                  <span
                    style="color: #409eff; cursor: pointer"
                    @click="visible = true"
                    >立即查看</span
                  >
                </p>
              </a-space>
            </a-col>
          </a-row>
          <a-row class="grid-demo">
            <a-col flex="70px">
              <div
                style="line-height: 32px; margin-right: 10px; color: #6b6b6b"
              >
                适用部门
              </div>
            </a-col>
            <a-col :flex="1">
              <a-space direction="vertical" fill>
                <a-input
                  @click="isDepartmentShow"
                  v-model="departmentName"
                  placeholder="请输入"
                />
                <TableTurn
                  style="width: 100%"
                  :isShowPagination="false"
                  :tableData="getTableDataDepartment"
                  ref="tableRefDepartment"
                >
                  <a-table-column
                    align="center"
                    data-index="name"
                    title="部门名称"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    data-index="attendanceTeamMember"
                    title="在此考勤组人数"
                  >
                  </a-table-column>
                  <a-table-column
                    align="center"
                    data-index="notAttendanceTeamMember"
                    title="未在此考勤组人数"
                  >
                    <template #cell="{ record, rowIndex }">
                      <p
                        style="color: #409eff; cursor: pointer"
                        @click="
                          record?.notAttendanceTeamMember &&
                            changeDepartmentList(
                              record.notAttendanceTeamData,
                              rowIndex
                            )
                        "
                      >
                        {{ record?.notAttendanceTeamMember }}
                      </p>
                    </template>
                  </a-table-column>
                </TableTurn>
              </a-space>
            </a-col>
          </a-row>
        </a-space>
      </a-form-item>
    </a-form>
  </main>
  <OrganizationPersonnel
    ref="organizationPersonnel"
    :selected-ids="personnelIds.data"
    @changePersonnel="changePersonnel"
  />

  <OrganizationDepartment
    ref="organizationDepartment"
    :selected-ids="departmentIds.data"
    @changePersonnel="changeDepartment"
  />
  <a-drawer
    :width="450"
    :visible="visible"
    @ok="handleOk"
    @cancel="visible = false"
    unmountOnClose
  >
    <template #title> 未在此考勤组人员 </template>
    <a-space direction="vertical" fill>
      以下成员已加入其他考勤组，请选择是否加入此考勤组
      <TableTurn
        :isShowPagination="false"
        :tableData="getTableData"
        ref="tableRef"
        :args="{
          rowSelection: {
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false
          }
        }"
      >
        <a-table-column align="center" data-index="name" title="姓名">
        </a-table-column>
        <a-table-column align="center" data-index="name" title="所在考勤组">
          <template #cell="{ record }">
            {{ record?.attendanceTeam?.name || '暂无' }}
          </template>
        </a-table-column>
      </TableTurn>
    </a-space>
  </a-drawer>
  <a-drawer
    :width="450"
    :visible="departmentVisible"
    @ok="handleDepartmentVisibleOk"
    @cancel="departmentVisible = false"
    unmountOnClose
  >
    <template #title> 未在此考勤组人员 </template>
    <a-space direction="vertical" fill>
      以下成员已加入其他考勤组，请选择是否加入此考勤组
      <TableTurn
        :isShowPagination="false"
        :tableData="getDepartmentTableData"
        ref="tableRefDepartmentList"
        :args="{
          rowSelection: {
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false
          }
        }"
      >
        <a-table-column align="center" data-index="name" title="姓名">
        </a-table-column>
        <a-table-column align="center" data-index="name" title="所在考勤组">
          <template #cell="{ record }">
            {{ record?.attendanceTeam?.name || '暂无' }}
          </template>
        </a-table-column>
      </TableTurn>
    </a-space>
  </a-drawer>
</template>

<script lang="ts" setup>
import {
  GetWorkCalendarList,
  GetAttendanceCycle,
  GetClassesManage,
  GetAttendanceRemitUserList,
  PostClasses,
  PutClasses
} from '@/apis/attendance/base-setting/index';
import OrganizationPersonnel from '@/components/OrganizationPersonnel/index.vue';
import OrganizationDepartment from '@/components/OrganizationDepartment/index.vue';
import { GetSectionPersonnel } from '@/apis/management/human/baseSetting/leaveSetting';

const route = useRoute();
const id = route.query.id;
const visible = ref(false);
const departmentVisible = ref(false);
const organizationPersonnel = ref();
const organizationDepartment = ref();
const form = reactive<any>({
  schedulingOfficerId: [],
  attendanceTeamMember: []
});
const departmentList = reactive({ data: [] });
let type = ref(0);
const fieldNames = { value: 'id', label: 'name' };
let personnelIds: { data: number[] } = reactive({ data: [] });
let applicableEmployeesIds: { data: number[] } = reactive({ data: [] });
const calendarData: any = reactive({ data: [] });
const cycleData: any = reactive({ data: [] });
const attendanceClassesSettingList: any[] = reactive([]);
const schedulingOfficer = ref();
const attendanceTeam = ref();
const departmentName = ref();
const tableRef = ref();
const tableRefDepartment = ref();
const tableRefDepartmentList = ref();
const remitUserList: any = reactive({ data: [] });
const init = async () => {
  const res = await GetWorkCalendarList({ pageNumber: 0, pageSize: -1 });
  const res1 = await GetAttendanceCycle({ pageNumber: 0, pageSize: -1 });
  const res2 = await GetAttendanceRemitUserList({
    type: 1,
    pageNumber: 0,
    pageSize: -1
  });
  remitUserList.data = res2.content;
  cycleData.data = res1.content;
  calendarData.data = res.content;
};
init();

const attendanceClassesSettingData = computed(() => {
  if (form?.attendanceClassesType)
    return attendanceClassesSettingList[form?.attendanceClassesType];
  else return [];
});
const getAttendanceClassesSettingData = async (e: 1 | 2 | 3 | 4) => {
  form.attendanceClassesSettingId = [];
  if (!attendanceClassesSettingList[e]) {
    const res = await GetClassesManage({
      type: e,
      pageNumber: 0,
      pageSize: -1
    });
    res.content.forEach((ele: any) => {
      // if (ele.type !== 1) {
      ele.disabled = true;
      ele.children = ele.attendanceClassesSetting;
      // }
    });
    attendanceClassesSettingList[e] = res.content;
  }
};
const changePersonnel = (data: any) => {
  if (type.value === 1) {
    form.schedulingOfficerId = data.ids;
    schedulingOfficer.value = data.data?.map(({ name }: any) => name).join(',');
  } else if (type.value === 2) {
    applicableEmployeesIds.data = data.ids;
    form.attendanceTeamMember = form.attendanceTeamMember?.filter(
      ({ applicableEmployee }: any) => applicableEmployee !== 1
    );
    applicableEmployeesExist.data.length = 0;
    console.log(
      ' applicableEmployeesExist.data',
      data,
      applicableEmployeesExist.data
    );

    ApplicableEmployees(data.data);
  }
};

const applicableEmployeesExist: any = reactive({ data: [] });

const ApplicableEmployees = (data: any[]) => {
  for (const { name, id, departmentId } of data) {
    const res = remitUserList.data?.filter((ele: any) => ele.id === id)[0];
    if (res?.attendanceTeamMember) {
      res.attendanceTeamMember.name = name;
      applicableEmployeesExist.data?.push(res.attendanceTeamMember);
    } else {
      form.attendanceTeamMember?.push({
        name,
        userId: id,
        departmentId,
        type: 1,
        applicableEmployee: 1,
        applicableDepartment: 2
      });
    }
  }
  attendanceTeam.value = form.attendanceTeamMember
    ?.filter(({ applicableEmployee }: any) => applicableEmployee === 1)
    ?.map(({ name }: any) => name)
    .join(',');
};
const getTableData = () => {
  try {
    return applicableEmployeesExist.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const getDepartmentTableData = () => {
  try {
    return departmentList.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const departmentData: any = reactive({ data: [] });
const departmentIds: { data: number[] } = reactive({ data: [] });
const getTableDataDepartment = () => {
  try {
    return departmentData.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const isShow = (num: 1 | 2) => {
  type.value = num;
  if (type.value === 1) {
    personnelIds.data = form.schedulingOfficerId;
  } else if (type.value === 2) {
    personnelIds.data = applicableEmployeesIds.data;
  }
  organizationPersonnel.value.show();
};

const isDepartmentShow = () => {
  organizationDepartment.value.show();
};

const changeDepartment = async (data: any) => {
  departmentIds.data = data.ids;
  departmentName.value = data.data?.map(({ name }: any) => name).join(',');
  departmentData.data.length = 0;
  for (const item of data.data) {
    const departmentList = await GetSectionPersonnel({
      type: item.node === '部门' ? 2 : 1,
      typeName: item.id
    });
    applicableEmployeesIds.data;
    const newData: any = { name: item.name };
    newData.attendanceTeamMember = departmentList?.filter(({ id }: any) =>
      applicableEmployeesIds.data?.includes(id)
    ).length;
    newData.notAttendanceTeamData = departmentList?.filter(
      ({ id }: any) => !applicableEmployeesIds.data?.includes(id)
    );
    newData.notAttendanceTeamMember = newData.notAttendanceTeamData.length;
    departmentData.data?.push(newData);
  }
};

const changeDepartmentListIndex = ref(0);

const changeDepartmentList = (data: any, rowIndex: number) => {
  departmentList.data = data;
  departmentVisible.value = true;
  changeDepartmentListIndex.value = rowIndex;
};

const handleOk = () => {
  if (
    tableRef.value.selectedListData &&
    tableRef.value.selectedListData.length !== 0
  ) {
    tableRef.value.selectedListData.forEach(
      ({ id, userId, departmentId, name }: any) => {
        form.attendanceTeamMember?.push({
          id,
          name,
          userId,
          departmentId,
          type: 1,
          applicableEmployee: 1,
          applicableDepartment: 2
        });
      }
    );
    attendanceTeam.value = form.attendanceTeamMember
      ?.filter(({ applicableEmployee }: any) => applicableEmployee === 1)
      ?.map(({ name }: any) => name)
      .join(',');
    applicableEmployeesExist.data = applicableEmployeesExist.data?.filter(
      ({ id }: any) => !tableRef.value.selectedList?.includes(id)
    );
    tableRef.value.loadData();
  }
  visible.value = false;
};

const handleDepartmentVisibleOk = () => {
  if (
    tableRefDepartmentList.value.selectedListData &&
    tableRefDepartmentList.value.selectedListData.length !== 0
  ) {
    tableRefDepartmentList.value.selectedListData.forEach(
      ({ id, departmentId }: any) => {
        form.attendanceTeamMember?.push({
          userId: id,
          departmentId,
          type: 1,
          applicableEmployee: 2,
          applicableDepartment: 1
        });
      }
    );
    const length = tableRefDepartmentList.value.selectedListData.length;
    departmentData.data[changeDepartmentListIndex.value].notAttendanceTeamData =
      departmentData.data[
        changeDepartmentListIndex.value
      ].notAttendanceTeamData?.filter(
        ({ id }: any) =>
          !tableRefDepartmentList.value.selectedList?.includes(id)
      );
    departmentData.data[changeDepartmentListIndex.value].attendanceTeamMember =
      departmentData.data[changeDepartmentListIndex.value]
        .attendanceTeamMember + length;
    departmentData.data[
      changeDepartmentListIndex.value
    ].notAttendanceTeamMember =
      departmentData.data[changeDepartmentListIndex.value]
        .notAttendanceTeamMember - length;
    tableRefDepartment.value.loadData();
  }
  departmentList.data = [];
  changeDepartmentListIndex.value = 0;
  departmentVisible.value = false;
};

const save = async () => {
  console.log('save', form);

  if (form.id) {
    await PutClasses(form);
  } else {
    await PostClasses(form);
  }
};
onMounted(() => {
  const data = JSON.parse(localStorage.getItem('classesData') + '');
  getAttendanceClassesSettingData(data?.attendanceClassesType);
  Object.assign(form, data);
  schedulingOfficer.value = form.schedulingOfficer
    ?.map(({ name }: any) => name)
    .join('、');
  applicableEmployeesIds.data = form.employee?.map(({ id }: any) => id);
  attendanceTeam.value = form.employee
    ?.map(({ userInfo }: any) => userInfo.name)
    .join('、');
  departmentIds.data = form.department?.map(({ id }: any) => id);
  departmentName.value = form.department
    ?.map(({ name }: any) => name)
    .join('、');
});
onUnmounted(() => {
  localStorage.removeItem('classesData');
});
defineExpose({ save });
</script>

<style lang="less" scoped>
main {
  margin-bottom: 60px;
  overflow: hidden;
  padding: 10px 20px;

  header {
    h2 {
      display: flex;
      align-items: center;
      padding-bottom: 10px;
      border-bottom: 1px solid #f2f2f2;
      &::before {
        content: '';
        display: inline-block;
        width: 7px;
        height: 30px;
        background-color: #165dff;
        margin-right: 10px;
      }
    }
  }
}
:deep(.arco-table-th),
:deep(.arco-table-td) {
  height: 60px;
}
:deep(.arco-collapse-item-content) {
  background-color: #fff;
}
</style>
